package calao.storage.bdb;

import static calao.util.Logger.log;

import com.sleepycat.je.SecondaryDatabase;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.LockMode;

class SecondaryCursor
extends BdbCursor
{

	com.sleepycat.je.SecondaryCursor bdbCursor;
	DatabaseEntry hitSecondaryKey = new DatabaseEntry();

	SecondaryCursor(SecondaryDatabase db) 
	{
		try {
			bdbCursor = db.openSecondaryCursor(null, null);
		}
		catch (DatabaseException e) {
			throw new RuntimeException(e);
		}
		this.hitKey = new DatabaseEntry();
	}

	public void close() 
	{
		try {
			if (bdbCursor!=null) bdbCursor.close();
		}
		catch (DatabaseException e) {
			log(e);
		}
		finally {
			bdbCursor = null;
		}
	}

	@Override
	OperationStatus doGetFirst() 
	throws DatabaseException 
	{
		return bdbCursor.getFirst(hitSecondaryKey, hitKey, getHitData(), 
				LockMode.DEFAULT);
	}

	@Override
	OperationStatus doGetNext() 
	throws DatabaseException 
	{
		return bdbCursor.getNext(hitSecondaryKey, hitKey, getHitData(), 
				LockMode.DEFAULT);
	}

	@Override
	OperationStatus doGetSearchKey(DatabaseEntry key) 
	throws DatabaseException 
	{
		hitSecondaryKey = Util.copy(key);
		return bdbCursor.getSearchKey(hitSecondaryKey, hitKey, getHitData(), 
				LockMode.DEFAULT);
	}

	@Override
	OperationStatus doGetNextDup() 
	throws DatabaseException 
	{
		return bdbCursor.getNextDup(hitSecondaryKey, hitKey, getHitData(), 
				LockMode.DEFAULT);
	}

	@Override
	OperationStatus doGetSearchKeyRange(DatabaseEntry key) 
	throws DatabaseException 
	{
		hitSecondaryKey = Util.copy(key);
		return bdbCursor.getSearchKeyRange(hitSecondaryKey, hitKey, getHitData(), 
				LockMode.DEFAULT);
	}

	@Override
	DatabaseEntry getSearchedKey() 
	{
		return hitSecondaryKey;
	}	

	@Override
	OperationStatus doDelete()
	throws DatabaseException
	{
		return bdbCursor.delete();
	}

	@Override
	OperationStatus doSet(DatabaseEntry data) 
	throws DatabaseException 
	{
		// secondary bdb cursor does not support putCurrent(data)
		// TODO find an alternative to SecondaryCursor.putCurrent(data)
		return bdbCursor.putCurrent(data);
	}

}
